package com.weixing.mall.provider.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.weixing.mall.provider.api.model.query.ActGoodsQuery;
import com.weixing.mall.provider.api.model.vo.ActivityProductVo;
import com.weixing.mall.provider.api.model.vo.ItemVo;
import com.weixing.mall.provider.api.model.vo.UserInfoVo;
import com.weixing.mall.provider.api.service.ItemFeign;
import com.weixing.mall.provider.api.service.SysUserRpcService;
import com.weixing.mall.provider.mapper.OrderGoodsMapper;
import com.weixing.mall.provider.mapper.OrderMapper;
import com.weixing.mall.provider.model.domain.OrderGoods;
import com.weixing.mall.provider.model.query.CommoditySalesQuery;
import com.weixing.mall.provider.model.vo.CommoditySalesVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CommodityDepartServiceImpl {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderGoodsMapper orderGoodsMapper;
    @Autowired
    private ItemFeign itemFeign;
    @Autowired
    private SysUserRpcService sysUserRpcService;


    public IPage<CommoditySalesVo> findCommodityDepartSale(Page page, CommoditySalesQuery commoditySalesQuery) {
        //第一步查询判定是否需要查询货品id集合
        if (commoditySalesQuery.getCatId() == null && commoditySalesQuery.getGoodsSn() == null && commoditySalesQuery.getProductSn() == null) {
            ActGoodsQuery query = new ActGoodsQuery();
            BeanUtils.copyProperties(commoditySalesQuery, query);
            List<Long> productId = itemFeign.findActProductVo(query).getData().stream().map(ActGoodsQuery -> ActGoodsQuery.getId()).collect(Collectors.toList());
            Long[] productIds = new Long[productId.size()];
            productId.toArray(productIds);
            commoditySalesQuery.setProductIds(productIds);
        }
        if (commoditySalesQuery.getStartTime() == null) {
            commoditySalesQuery.setStartTime(DateUtil.format(DateUtil.offset(new Date(), DateField.MONTH, -1), "yyyy-MM-dd"));
        }
        if (commoditySalesQuery.getEndTime() == null) {
            commoditySalesQuery.setEndTime(DateUtil.format(new Date(), "yyyy-MM-dd"));
        }
        //查询订单基础信息获取货品id号已经货品售卖数量
        IPage<CommoditySalesVo> tmpList = orderMapper.findCommodityDepartSale(page, commoditySalesQuery, commoditySalesQuery.getProductIds());//查询货品号和货品数量
        //调动货品RPC前数据准备工作，
        long[] tmp = queryProductIds(page, commoditySalesQuery);
        //根据货品id获取货品的详细信息
        List<ActivityProductVo> resultList = itemFeign.findActProductVoByIds(tmp).getData();
        //组装货品信息和货品售卖信息
        for (CommoditySalesVo cvo : tmpList.getRecords()) {
            Long productId = cvo.getProductId();
            for (ActivityProductVo vo : resultList) {
                Long compareproductId = vo.getId();
                if (compareproductId.equals(productId)) {
                    BeanUtils.copyProperties(vo, cvo);
                    UserInfoVo uservo = sysUserRpcService.userInfo(vo.getCreatedById()).getData();
                    cvo.setCreatedName(uservo.getUserName());
                }
            }
        }
        return tmpList;
    }

    /*销售明细报表*/

    public IPage<CommoditySalesVo> commodityDepartSaleDetails(Page page, CommoditySalesQuery commoditySalesQuery) {
        IPage<CommoditySalesVo> result = page;
        //第一步判定按照货号查询还是按照负责人查询
        if (commoditySalesQuery.getCreatedById() != null) {//按照负责人进行查找
            //首先查询该负责人负责的商品信息
            IPage<ActivityProductVo> list = itemFeign.findProductVoByCreatedId(page, commoditySalesQuery.getCreatedById()).getData();
            List<Long> productList = list.getRecords().stream().map(ActivityProductVo -> ActivityProductVo.getId()).collect(Collectors.toList());
            //然后根据商品的货品id号查询订单商品。
            List<OrderGoods> tmpList = orderGoodsMapper.selectList(new QueryWrapper<OrderGoods>().in("product_id", productList));
            //数据进行拼装
            List<CommoditySalesVo> resultVo = packingData(list.getRecords(),tmpList);
            result.setRecords(resultVo);
            result.setTotal(list.getTotal());
        }
        if (commoditySalesQuery.getProductId() != null) {
            //查询该货品的销售数据
            List<OrderGoods> list = orderGoodsMapper.selectList(new QueryWrapper<OrderGoods>().eq("product_id", commoditySalesQuery.getProductId()));
            //查询该货品的属性
            ActGoodsQuery query = new ActGoodsQuery();
            query.setProductId(commoditySalesQuery.getProductId());
            List<ActivityProductVo> productVos = itemFeign.findActProductVo(query).getData();
            ActivityProductVo productVo = productVos.size() == 0 ? null : productVos.get(0);
            CommoditySalesVo resultVo = new CommoditySalesVo();
            int[] tmpCombination = combination(productVo, list);
            BeanUtils.copyProperties(productVo, resultVo);
            resultVo.setOrderNum(productVos.size());
            resultVo.setOutStockNum(tmpCombination[1]);
            resultVo.setCancelNum(tmpCombination[2]);
            resultVo.setReturnNum(tmpCombination[3]);
            result.setCurrent(page.getCurrent());
            result.setPages(page.getPages());
            result.setTotal(productVos.size());
            List<CommoditySalesVo> resultList = Lists.newArrayList();
            resultList.add(resultVo);
            result.setRecords(resultList);
        }
        return result;
    }

    /*
     * 商品部销售报表首页
     * */

    public IPage<CommoditySalesVo> commodityDepartSaleIndex(Page page, CommoditySalesQuery commoditySalesQuery) {
        IPage<CommoditySalesVo> result = page;
        //第一步查询所有符合条件的货品ID集合
        long[] tmp = queryProductIds(page, commoditySalesQuery);
       if(tmp.length==0){//无数据则直接返回结果
           return result;
       }
        //第二步根据集合获取商品信息
        List<ActivityProductVo> resultList = itemFeign.findActProductVoByIds(tmp).getData();
        //第三步根据货品ID获取订单集合
        List<OrderGoods> tmpList = orderGoodsMapper.selectList(new QueryWrapper<OrderGoods>().in("product_id", tmp));
        //第四步进行数据的拼装
        List<CommoditySalesVo> resultVo = packingData(resultList,tmpList);
        result.setRecords(resultVo);
        result.setTotal(resultList.size());
        return result;
    }


    public IPage<CommoditySalesVo> findByproductStatus(Page page, CommoditySalesQuery commoditySalesQuery) {
        //第一步根据集合获取商品信息
        ItemVo  itemVo = itemFeign.findById(commoditySalesQuery.getProductId()).getData();
        IPage<CommoditySalesVo>  list=orderGoodsMapper.listByProductStatus(page,commoditySalesQuery);
            Long productId = itemVo.getId();
            for(CommoditySalesVo commoditySalesVo:list.getRecords()){
                Long comperProductId=commoditySalesVo.getProductId();
                if(productId.equals(comperProductId)){
                    BeanUtils.copyProperties(itemVo,commoditySalesVo);
                }
            }
        return list;
    }

    /*
* 数据组合
*
* */
    private int[] combination(ActivityProductVo activityProduct, List<OrderGoods> orderGoodsList) {
        int[] resulut = new int[4];
        int outStockNum = 0;
        int cancelNum = 0;
        int returnNum = 0;
        int orderNum = 0;
        Long productId = activityProduct.getId();
        for (OrderGoods orderGoods : orderGoodsList) {
            Long comperProductId = orderGoods.getProductId();
            if (productId.equals(comperProductId)) {
                orderNum += 1;
                int productStatu = orderGoods.getProductStatus();
                switch (productStatu) {
                    case 6:
                        outStockNum = +1;
                        break;
                    case 7:
                        cancelNum = +1;
                        break;
                    case 9:
                        returnNum = +1;
                        break;
                    default:

                }
            }
        }
        resulut[0] = orderNum;
        resulut[1] = outStockNum;
        resulut[2] = cancelNum;
        resulut[3] = returnNum;
        return resulut;
    }
/*
* 查询符合条件的商品集合
*
* */
    private long[] queryProductIds(Page page, CommoditySalesQuery commoditySalesQuery) {
        IPage<CommoditySalesVo> list = orderMapper.findCommodityDepartSale(page, commoditySalesQuery, commoditySalesQuery.getProductIds());
        List<Long> productList = list.getRecords().stream().map(CommoditySalesVo -> CommoditySalesVo.getProductId()).collect(Collectors.toList());
        Long[] productIds = new Long[productList.size()];
        productList.toArray(productIds);
        long[] tmp = new long[productIds.length];
        for (int i = 0; i < productIds.length; i++) {
            tmp[i] = productIds[i];
        }
        return tmp;
    }
    /*
    * 数据进行拼装
    *
    * */

    private  List<CommoditySalesVo>  packingData( List<ActivityProductVo> list,List<OrderGoods> tmpList  ){
        List<CommoditySalesVo> resultVo = Lists.newArrayList();
        for (ActivityProductVo productVo : list) {
            int[] tmpCombination = combination(productVo, tmpList);
            CommoditySalesVo commoditySalesVo = new CommoditySalesVo();
            productVo.setOrderNum(tmpCombination[0]);
            productVo.setOutStockNum(tmpCombination[1]);
            productVo.setCancelNum(tmpCombination[2]);
            productVo.setReturnNum(tmpCombination[3]);
            BeanUtils.copyProperties(productVo, commoditySalesVo);
            resultVo.add(commoditySalesVo);
        }
        return  resultVo;
    }
}
